package henu.cn.androidhomework.Login;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import henu.cn.androidhomework.MainActivity;
import henu.cn.androidhomework.R;

public class LoginActivity extends AppCompatActivity {
    private EditText etUserName;
    private EditText etPassword;
    private Drawable drawable_user;
    private Drawable drawable_cancel;
    private Drawable drawable_pwd;
    private Button forgotPassword;
    private Button registeredUser;

    private SharedPreferences pref;
    private SharedPreferences.Editor mEditor;

    private CheckBox remCheckBox;
    private TextView tv_login;

    private String smsid;//用于接收来自注册界面返回的表ID
    private String userPhone;
    private String userPassword;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Bmob.initialize(this, "f37ce38de3435d43b37d223c1d7cfd6d");

        //控制登录用户名图标大小
        etUserName = (EditText) findViewById(R.id.et_user);
        etPassword = (EditText) findViewById(R.id.et_password);
        drawable_user = getResources().getDrawable(R.drawable.user);
        drawable_pwd = getResources().getDrawable(R.drawable.password);

        drawable_user.setBounds(0, 0, 60, 60);//第一个 0 是距左边距离，第二个 0 是距上边距离，60 分别是长宽
        drawable_pwd.setBounds(0, 0, 60, 60);

        etUserName.setCompoundDrawables(drawable_user, null, null, null);//只放左边
        etPassword.setCompoundDrawables(drawable_pwd, null, null, null);


        /**
         * 从bmob后台获取数据实现登录功能
         */
        Intent intent1 = getIntent();
        smsid = intent1.getStringExtra("id");

        new Thread(new Runnable() {
            @Override
            public void run() {
//查找Person表里面id为6b6c11c537的数据


                BmobQuery<DB> bmobQuery = new BmobQuery<DB>();
                bmobQuery.getObject("ae3b4c0602", new QueryListener<DB>() {
                    @Override
                    public void done(DB db, BmobException e) {
                        if (e == null) {
                            showToast("查询成功");
                             userPhone = db.getPhonenumber();
                             userPassword = db.getPassword();
                        } else {
                            showToast("查询失败：" + e.getMessage());
                        }
                    }
                });
            }
        }).start();

        //实现记住密码
        pref = PreferenceManager.getDefaultSharedPreferences(this);
        pref = getSharedPreferences("acount", Context.MODE_PRIVATE);
        remCheckBox = (CheckBox) findViewById(R.id.remember_pass);
        boolean isRemember = pref.getBoolean("remember", false);

        etUserName = (EditText) findViewById(R.id.et_user);
        etPassword = (EditText) findViewById(R.id.et_password);
        if (isRemember) {
            //将账号和密码恢复到文本框
            String account = pref.getString("account", "");
            String pass = pref.getString("pass", "");
            etUserName.setText(account);
            etPassword.setText(pass);
            remCheckBox.setChecked(true);
        }
        tv_login = (TextView) findViewById(R.id.tv_login);
        tv_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = etUserName.getText().toString();
                String password = etPassword.getText().toString();
                // 如果账号是admin且密码是123456，就认为登录成功
                //if (account.equals("15093693856") && password.equals("123456")) {
                if (account.equals(userPhone) && password.equals(userPassword)) {
                    mEditor = pref.edit();
                    if (remCheckBox.isChecked()) {
                        mEditor.putBoolean("remember", true);
                        mEditor.putString("pass", password);
                        mEditor.putString("account", account);
                    } else {
                        mEditor.clear();
                    }
                    mEditor.apply();
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "account or password is invalid",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        etUserName.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                /**
                 * 顺序为左、上、右、下
                 */
                if (etUserName.getText().toString() != null || etUserName.getText().toString() != "") {
                    drawable_cancel = getResources().getDrawable(R.drawable.cancel);
                    drawable_cancel.setBounds(0, 0, 50, 50);
                    Toast.makeText(LoginActivity.this, etUserName.getText().toString(), Toast.LENGTH_LONG).show();
                    etUserName.setCompoundDrawables(drawable_user, null, drawable_cancel, null);//只放左边
                    //etPassword.setCompoundDrawables(drawable_pwd, null, drawable_cancel, null);
                }
                Drawable drawable = etUserName.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null)
                    return false;
                //如果不是按下事件，不再处理
                if (event.getAction() != MotionEvent.ACTION_UP)
                    return false;
                if (event.getX() > etUserName.getWidth()
                        - etUserName.getPaddingRight()
                        - drawable.getIntrinsicWidth() +
                        500) {//通过加(减)650来控制图片事件的触摸范围
                    etUserName.setText("");
                }
                return false;
            }
        });
        etPassword.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                /**
                 * 顺序为左、上、右、下
                 */
                //etPassword.setText("");
                if (etPassword.getText().length() == 0) {
                    drawable_cancel = getResources().getDrawable(R.drawable.cancel);
                    drawable_cancel.setBounds(0, 0, 50, 50);
                    // Toast.makeText(LoginActivity.this, etUserName.getText().toString(),Toast.LENGTH_LONG).show();
                    etPassword.setCompoundDrawables(drawable_pwd, null, drawable_cancel, null);//只放左边
                    //etUserName.setCompoundDrawables(drawable_user, null, drawable_cancel, null);//只放左边
                    // .setCompoundDrawables(drawable_pwd, null, drawable_cancel, null);
                }
                Drawable drawable = etPassword.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null)
                    return false;
                //如果不是按下事件，不再处理
                if (event.getAction() != MotionEvent.ACTION_UP)
                    return false;
                if (event.getX() > etPassword.getWidth()
                        - etPassword.getPaddingRight()
                        - drawable.getIntrinsicWidth() + 500) {
                    etPassword.setText("");
                }
                return false;
            }
        });

        forgotPassword = (Button) findViewById(R.id.forgotPassword);
        registeredUser = (Button) findViewById(R.id.registeredUser);
        //点击转到<忘记密码界面>
        forgotPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, forgotPassword.class);
                startActivity(intent);
            }
        });
        //点击转到<注册账户界面>
        registeredUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, registeredUser.class);
                startActivity(intent);
            }
        });
    }

    public void showToast(String msg) {
        Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_LONG).show();
    }
/**
 *  Bmob.initialize(this, "f37ce38de3435d43b37d223c1d7cfd6d");
 * //        Person p2 = new Person();
 * //        p2.setName("杨校庆");
 * //        p2.setAddress("河南开封");
 * //        p2.save(new SaveListener<String>() {
 * //            @Override
 * //            public void done(String objectId, BmobException e) {
 * //                if (e == null) {
 * //                    Toast.makeText(MainActivity.this, "添加数据成功，返回objectId为：" + objectId, Toast.LENGTH_LONG).show();
 * //                } else {
 * //                    Toast.makeText(MainActivity.this,"创建数据失败：" + e.getMessage(),Toast.LENGTH_LONG).show();
 * //
 * //                }
 * //            }
 * //        });
 *
 *         //查找Person表里面id为6b6c11c537的数据
 * //        final BmobQuery<Person> bmobQuery = new BmobQuery<>();
 * //        bmobQuery.getObject("0b7b77fc22", new QueryListener<Person>() {
 * //            @Override
 * //            public void done(Person person, BmobException e) {
 * //                if(e==null){
 * //                    Toast.makeText(MainActivity.this, "查询成功--" + person.getName()+"-"+person.getAddress(), Toast.LENGTH_LONG).show();
 * //text.setText("查询成功--" + person.getName().toString()+"-"+person.getAddress().toString());
 * //                }else{
 * //                    Toast.makeText(MainActivity.this, "查询失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
 * //
 * //                }
 * //            }
 * //        });
 * //        String picPath = "sdcard/temp.jpg";
 * //        final BmobFile bmobFile = new BmobFile(new File(picPath));
 * //        bmobFile.uploadblock(new UploadFileListener() {
 * //            @Override
 * //            public void done(BmobException e) {
 * //                if (e == null) {
 * //                    //bmobFile.getFileUrl()--返回的上传文件的完整地址
 * //                    Toast.makeText(MainActivity.this, "上传文件成功:" + bmobFile.getFileUrl(), Toast.LENGTH_LONG).show();
 * //
 * //                } else {
 * //                    Toast.makeText(MainActivity.this, "上传文件失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
 * //                }
 * //            }
 * //        });
 * //
 *         //BmobSMS.requestSMSCode()
 *         BmobSMS.requestSMSCode("15093693856", "DataSDK", new QueryListener<Integer>() {
 *             @Override
 *             public void done(Integer smsId, BmobException e) {
 *                 if (e == null) {
 *                     text.setText("发送验证码成功，短信ID：" + smsId + "\n");
 *                 } else {
 *                     text.setText("发送验证码失败：" + e.getErrorCode() + "-" + e.getMessage() + "\n");
 *                 }
 *             }
 *         });
 *
 *     }
 * }
 */
}

